package com.mmsj;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class SharedPreferenceActivity extends AppCompatActivity {
    private EditText et_username;
    private EditText et_password;
    private CheckBox cb;
    private Button btnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shared_preference);
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        cb = findViewById(R.id.cb_remember_pwd);
        btnLogin = findViewById(R.id.btn_login);

        // TODO 检查是否有保存的用户信息，如果有，则显示

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String username = et_username.getText().toString().trim();
                String password = et_password.getText().toString().trim();
                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(SharedPreferenceActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    // 登陆
                    if (cb.isChecked()) {
                        SharedPreferences mySp = getSharedPreferences("mySp", MODE_PRIVATE);
//                        打开编辑器
                        SharedPreferences.Editor editor = mySp.edit();
                        // 写入信息
                        editor.putString("username", username);
                        editor.putString("password", password);
                        editor.commit();
                        Toast.makeText(SharedPreferenceActivity.this, "保存信息成功", Toast.LENGTH_SHORT).show();
                    }
                    // 登陆
                    if ("zhangsan".equals(username) && "123".equals(password)) {
                        Toast.makeText(SharedPreferenceActivity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(SharedPreferenceActivity.this, "登陆失败", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

    }
}